package channelService

import (
	"errors"
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/FileName"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"io/ioutil"
)

type channelService struct {
	recv2rspd     map[string]string
	recv2rsrd     map[string]string
	channel2event map[string]string
}

func (e *channelService) initService() (err error) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			msg := fmt.Sprintf("异常信息：%v", r)

			err = errors.New(msg)
			commLogger.Console.Error(msg)
		}
	}()

	e.recv2rspd = map[string]string{}
	e.recv2rsrd = map[string]string{}
	e.channel2event = map[string]string{}

	// 获得当前配置文件路径
	confFileName := FileName.GetOsFilePath(commEnv.Service.WorkDir + "/conf/" + commEnv.Service.ServiceType + "/" + commEnv.Service.ServiceName + "/" + "simulator.conf")

	// 读取文本文件内容
	file, err := ioutil.ReadFile(confFileName)
	if err != nil {
		commLogger.Error("读取文件出错:" + err.Error())
		return
	}

	// 将JSON格式的文件内容，转换为MAP
	datas := Json.BuildMapByJson(string(file))
	if datas == nil {
		commLogger.Error("文件格式不是合法的JSON格式")
		return
	}

	list := datas["channel_simulator"].([]interface{})
	for _, val := range list {
		data := val.(map[string]interface{})

		recv := data["recv"]
		rspd := data["rspd"]
		rsrd := data["rsrd"]

		channelName := data["channel_name"]
		event := data["event"]

		if recv != nil && rspd != nil {
			// 格式化数据
			recv = Hex.EncodeToString(Hex.DecodeString(recv.(string)))
			rspd = Hex.EncodeToString(Hex.DecodeString(rspd.(string)))
			e.recv2rspd[recv.(string)] = rspd.(string)
		}
		if recv != nil && rsrd != nil {
			recv = Hex.EncodeToString(Hex.DecodeString(recv.(string)))
			rsrd = Hex.EncodeToString(Hex.DecodeString(rsrd.(string)))
			e.recv2rsrd[recv.(string)] = rsrd.(string)
		}
		if channelName != nil && event != nil {
			// 格式化数据
			event = Hex.EncodeToString(Hex.DecodeString(event.(string)))
			e.channel2event[channelName.(string)] = event.(string)
		}
	}

	return nil
}

func (e *channelService) Execute(requestVO *commRedisRpc.ChannelRequestVO) (*commRedisRpc.ChannelRespondVO, error) {
	return execute.execute(e.recv2rspd, e.recv2rsrd, requestVO)
}

func (e *channelService) Report() ([]*commRedisRpc.ChannelRespondVO, error) {
	return report.popAll(commEnv.Service.ModelName, e.channel2event)
}
